package myJs.common

import myJs.Implicits._
import myJs.myPkg.RSelect.{Select, SelectOption}
import myJs.myPkg.jquery.{$, JQuery}
import myJs.myPkg.reactHookForm.{Controller, FieldR, RegisterOptions, UseFormRT}
import org.scalajs.dom.html.Form
import org.scalajs.dom.{Event, document, html}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.{React, ReactElement, ReactRef}
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.web.html._

import scala.collection.immutable.SeqMap
import scala.scalajs.js

/**
 * Created by yz on 21/1/2022
 */
@react object PureRSelectCp {

  case class Props(
                    optionMap: SeqMap[String, String],
                   onChange: String => Unit, name: String = "",
                   value: js.UndefOr[String] = js.undefined,
                   registerOptions: RegisterOptions = RegisterOptions(),
                   useForm: UseFormRT,
                  )

  val component = FunctionalComponent[Props] { props =>

    val divRef = React.createRef[html.Div]

    object FTool {

    }

    val valueOp = props.useForm.watch(props.name)

    useEffect(() => {
      valueOp.toSelectionOption.foreach { value =>
        props.onChange(value.value)
      }
    }, List(valueOp)
    )

    useEffect(() => {
      val selectOption = props.value.map { x =>
        SelectOption(value = x, label = x)
      }
      props.useForm.setValue(props.name, selectOption)
    }, List(props.value)
    )

    val options = props.optionMap.map { case (k, v) =>
      SelectOption(value = k, label = v)
    }.toList

    div(ref := divRef,
      Controller(
        name = props.name,
        control = props.useForm.control,
        rules = props.registerOptions,
        render = (fieldR: FieldR) => {
          val field = fieldR.field
          val fieldValue = field.value.toSelectionOption
          Select(
            onChange = field.onChange: js.Function1[SyntheticEvent[TagElement#RefType, Event], Unit],
            options = options, placeholder = "点击选择", name = field.name, value = fieldValue, ref = field.ref,
           ):ReactElement
        }
      ),
      if (props.useForm.formState.errors.isDefinedAt(props.name)) {
        small(className := "help-block", props.useForm.formState.errors(props.name).message)
      } else null

    )


  }

}
